package crossrun.tool.pdf2img.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.Future;

import crossrun.tool.pdf2img.control.ExeThreadServics;

public class PdfUtil {

    private Context context;
    private Future future;
    private File dir;

    public PdfUtil(Context context) {
        this.context = context;
        dir = context.getExternalFilesDir("pic");
    }

    public void start(final File pdfFile) {
        if (listener != null) {
            listener.onStart();
        }
        if (future != null && !future.isDone()) {
            future.cancel(true);
        }
        future = ExeThreadServics.obtain().getCachedThreadPool().submit(new Runnable() {
            @Override
            public void run() {
                String prex = FileUtils.splitFileName(pdfFile.getName())[0];
                File picDir = new File(dir, prex);
                FileUtils.deleteFile(picDir);
                picDir.mkdir();
                listener.onProcess(0, "开始提取图片");
                try {
                    getBitMaps(pdfFile, picDir,prex);
                    listener.onProcess(0, "提取图片完毕");
                    listener.onProcess(0, "开始压缩");
                    File dest = new File(
                            context.getExternalFilesDir("zip")
                            , prex+".zip");
                    if (dest.exists()) {
                        dest.delete();
                    }
                    ZipUtil.ZipFolder(picDir.getAbsolutePath(), dest.getAbsolutePath());
                    listener.onProcess(0, "压缩完毕");
                    listener.onSuccess(dest.getAbsolutePath());
                    Log.e("crossrun", dest.getAbsolutePath());
                } catch (Exception e) {
                    e.printStackTrace();
                    if (listener != null) {
                        listener.onFailed(e);
                    }
                }
            }
        });
    }

    private void getBitMaps(File pdfFile, File picDir, String prex) throws Exception {
        context.getExternalFilesDir("pic");

        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));
        final int pageCount = renderer.getPageCount();
        Log.e("test_sign", "图片de 张数： " + pageCount);
        listener.onProcess(0, "图片张数： " + pageCount);
        for (int i = 0; i < pageCount; i++) {
            listener.onProcess(0, String.format("正在提取第%d张图片", i));
            PdfRenderer.Page page = renderer.openPage(i);
            int width = context.getResources().getDisplayMetrics().densityDpi / 72 * page.getWidth();
            int height = context.getResources().getDisplayMetrics().densityDpi / 72 * page.getHeight();
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            // 以下三行处理图片存储到本地出现黑屏的问题，这个涉及到背景问题
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(Color.WHITE);
            canvas.drawBitmap(bitmap, 0, 0, null);
            Rect r = new Rect(0, 0, width, height);
            page.render(bitmap, r, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            saveImgFile(bitmap, i, picDir,prex);
            bitmap.recycle();
            bitmap = null;
            // close the page
            page.close();
        }
        // close the renderer
        renderer.close();

    }

    private void saveImgFile(Bitmap bitmap, int i, File picDir, String prex) throws Exception {
        listener.onProcess(0, String.format("正在保存第%d张图片", i));
        File file = new File(picDir, String.format("%s%04d.jpg", prex,i));
        FileOutputStream fos = null;
        fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void recycle() {
        context = null;
        listener = null;
        if (future != null && !future.isDone()) {
            future.cancel(true);
        }
    }

    private PdfTransListener listener;

    public void setListener(PdfTransListener listener) {
        this.listener = listener;
    }

    public interface PdfTransListener {
        void onStart();

        void onProcess(int p, String msg);

        void onSuccess(String zipPath);

        void onFailed(Throwable e);
    }
}
